import { _decorator, Component, Input, instantiate, Label, Node, Prefab, Sprite } from 'cc';
import { Datum, Http, LoadUrlImg, prepayType, ShoopData, shopbuyType } from '../../main/lib/Net';
import { BtnType } from '../../main/common/Alert';
import { Main } from '../../Main_/Main';
import { Util } from '../../main/lib/Util';
import { fund } from '../../main/common/fund';
import { Wechat } from '../../main/Market/Wechat';
import { TagLabel } from '../../main/common/TagLabel';
const { ccclass, property } = _decorator;

@ccclass('Shopping')
export class Shopping extends Component {
    @property(Node)
    LeftBtn: Node = null;//tab按钮节点组节点
    @property(Node)
    content: Node = null;//内容节点
    @property(Prefab)
    Item: Prefab = null;//商品卡片
    @property(Prefab) //按钮预制体
    BtnPre: Prefab = null;
    static idx: number = 0;
    /**显示指定按钮 金币|砖石|道具|装扮*/
    static ShowBtn(idx: 0 | 1 | 2 | 3, destroy: Node) {
        Main.ToggleUI("Shopping", destroy.name, true);
        this.idx = idx;
    }
    exit() { Main.ToggleUI("Home", this.node.name, true) };
    start() {
        const TabType: { [key: string]: number } = { "金币": 1, "钻石": 2, "道具": 3, '装扮': 4 };//数据类型
        for (const btnKey in TabType) {
            const btnNode = instantiate(this.BtnPre);
            const btnClass = btnNode.getComponent(TagLabel);
            btnClass.setLabel(btnKey, btnKey);
            if (Wechat.isiOS()) { //苹果平台不显示付费道具['钻石']
                if (btnKey !== '钻石') {
                    this.LeftBtn.addChild(btnNode);
                }
            } else {
                this.LeftBtn.addChild(btnNode);
            }

        }
        const tog = new Util.Toggle(this.LeftBtn);//设置toggle功能
        tog.onTag(key => {
            // console.log(key, "被按下了");
            let TabData: Datum[] = [];
            new Http<ShoopData>((suc) => {
                // console.log("商品列表", suc);
                if (suc.code === 0) {
                    suc.data.forEach(item => {//找到对应的商品数据
                        if (item.group === TabType[key]) TabData.push(item); //把grup和选中按钮所对应的数据添加到data里面去
                    });
                    // console.log(TabData, '商品数据');
                    this.content.children[0].active = TabData.length > 0;//显示商品卡片
                    this.content.children[1].active = !(TabData.length > 0);//显示暂无数据label
                    if (TabData.length > 0) {
                        this.content.children[0].removeAllChildren();//清空所有子元素
                        TabData.forEach(item => {
                            let goodsNode = instantiate(this.Item);
                            //按钮点击事件
                            goodsNode.on(Input.EventType.TOUCH_START, () => this.ply(item));
                            //请求并且设置商品图片
                            new LoadUrlImg().getFrame(item.image).then(imgdata => {
                                // console.log("图片数据",imgdata);
                                goodsNode.children[0].getComponent(Sprite).spriteFrame = imgdata;
                            }, rej => {
                                console.log("商城请求商品图片错误", rej);
                            })
                            //设置标题
                            goodsNode.children[1].getComponent(Label).string = item.name;
                            //设置价格
                            let price: string = '';//价格
                            switch (item.consume) {
                                case consumeType.gold: price = `${new Util.Format(item.price)} 金币`;
                                    break
                                case consumeType.diamond: price = `${new Util.Format(item.price)} 钻石`;
                                    break
                                case consumeType.rmb: price = `￥${(item.price / 100).toString()}`; //显示多少钱
                                    break
                            }
                            goodsNode.children[2].getComponent(Label).string = price;
                            this.content.children[0].addChild(goodsNode);
                        });
                    }
                }
            }).shoop();
        }, Shopping.idx);
    }
    getprice(type: consumeType, price: number) {
        if (type === consumeType.rmb) {//格式化人名币
            return price / 100;
        }
        return price;
    }
    getType(type: consumeType) {
        const data = {
            1: '金币',
            2: '钻石',
            3: '元'
        }
        return data[type]
    }
    ply(item: Datum) {
        // console.log("商品按钮事件yzt", item);
        new Util.Alert().ShowAlert({
            cancel: true,
            confrm: true,
            title: '提示',
            msg: `是否花费${this.getprice(item.consume, item.price)}${this.getType(item.consume)}购买${item.desc}?`,
            callfun: (arg, arg2) => {
                if (arg === BtnType.Confrm) {
                    new PayShop(item.consume, item)
                }
                arg2.destroy();
            },
        })
    }
}

enum consumeType {
    /**金币 */
    gold = 1,
    /**钻石 */
    diamond,
    /**人名币 */
    rmb,
}

class PayShop {
    http: Http<any> = null;
    type: consumeType = null;
    constructor(type: consumeType, data: Datum) {
        this.http = new Http(this.callfun.bind(this));
        this.type = type;
        const obj: any = Object.create(null);
        obj['goods_id'] = data.id;
        switch (type) {
            case consumeType.gold: this.notRMB(obj); break;
            case consumeType.diamond: this.notRMB(obj); break;
            case consumeType.rmb:
                obj['sandbox'] = true;
                this.RMB(obj);
                break;
        }
    }
    /**非人民币支付 */
    private notRMB(option: shopbuyType) {
        this.http.shopbuy(option);
        console.log('金币或者钻石币支付', option);
    }
    /**人民币支付 */
    private RMB(option: prepayType) {
        this.http.prepay(option);
        console.log('人名币支付', option);
    }
    callfun(data: { code: number, data: {}, msg: string }, url?: string) {
        console.log("http回传数据", data, this);
        if (this.type === consumeType.diamond || this.type === consumeType.gold) {    //如果是非人民币支付
            if (data.code === 0) {
                fund.I.init();//刷新金币显示
            }
            new Util.Alert().ShowAlert({//弹窗提示
                cancel: false,
                confrm: true,
                msg: data.msg,
                callfun: (arg, arg2) => {
                    arg2.destroy();
                },
            })
        }
        if (this.type === consumeType.rmb) {    //人名币支付
            console.log("人民币支付订单数据", data);
            interface da {
                buyQuantity: number
                outTradeNo: string
            }
            const data_: da = data.data as any;
            if (data.code === 0) {
                new Wechat().pay(data_.buyQuantity, data_.outTradeNo);
            }
            if (data.code === 7) {
                new Util.Alert().ShowAlert(
                    {
                        msg: data.msg,
                        cancel: false,
                        confrm: true,
                        callfun: (suc, node) => {
                            node.destroy()
                        }
                    }
                )
            }
        }
    }
}